﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace LeisureNcre.Helper
{
    public class HttpHelper
    {

        private static HttpHelper _instance = null;

        private static HttpClient _client;

        private static readonly object Locker = new object();

        public static HttpHelper Init(String BaseUrl)
        {
            if (_instance == null)
            {
                lock (Locker)
                {
                    if (_instance == null)
                    {
                        _instance = new HttpHelper(BaseUrl);
                    }
                }
            }
            return _instance;
        }

        private HttpHelper(String BaseUrl)
        {
            // 创建HTTPClient对象
            _client = new HttpClient();
            //设置连接超时时间
            _client.Timeout = TimeSpan.FromSeconds(30);
            // 开启连接池
            _client.DefaultRequestHeaders.ConnectionClose = false;
            //最大并发连接数
            ServicePointManager.DefaultConnectionLimit = 5;

        }

        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(int Description, int ReservedValue);
        #region 方法一
        /// <summary>
        /// 用于检查网络是否可以连接互联网,true表示连接成功,false表示连接失败
        /// </summary>
        /// <returns></returns>
        public bool IsConnectInternet()
        {
            int Description = 0;
            return InternetGetConnectedState(Description, 0);
        }
        #endregion 方法一

        #region Get请求
        /// <summary>
        /// 序列化返回值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="api"></param>
        /// <param name="strParams"></param>
        /// <returns></returns>
        public async Task<T> DoGet<T>(string api, Dictionary<string, string> strParams)
        {
            var res = await Get(api, strParams);
            return await res.Content.ReadFromJsonAsync<T>();
        }
        /// <summary>
        /// 序列化请求
        /// </summary>
        /// <param name="api"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> Get(string api, Dictionary<string, string> param)
        {
            if (param.Count > 0)
            {
                string paramStr = DictionaryToParams(param);
                return await _client.GetAsync(api + paramStr);
            }
            return await _client.GetAsync(api);
        }
        #endregion
        /// <summary>
        /// 序列化返回值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="api"></param>
        /// <param name="value"></param>
        /// <param name="strParams"></param>
        /// <returns></returns>
        public async Task<T> DoPost<T>(string api, object value, Dictionary<string, string> strParams)
        {
            var res = await Post(api, value, strParams);
            return await res.Content.ReadFromJsonAsync<T>();
        }

        #region Post请求
        /// <summary>
        /// 自定义的转发功能
        /// </summary>
        /// <param name="api"></param>
        /// <param name="dataname"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public Task<HttpResponseMessage> Post(string api, object value, Dictionary<string, string> param)
        {
            return _client.PostAsync(api + DictionaryToParams(param), new StringContent(JsonConvert.SerializeObject(value), Encoding.UTF8, "application/json"));
        }
        #endregion

        #region Put请求
        
        #endregion


        #region Delete请求
        
        #endregion
        /// <summary>
        /// 字典转参数
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string DictionaryToParams(Dictionary<string, string> param)
        {
            var res = "";
            if (param != null)
            {
                var list = param.ToList();
                if (list.Count != 0)
                {
                    for (var i = 0; i < list.Count; i++)
                    {

                        if (i != 0)
                        {
                            res += "&";
                        }
                        res += $"{list[i].Key}={list[i].Value}";
                    }
                    res = "?" + res;
                }

            }
            return res;
        }
    }
}
